// Valores uniformes
uniform mediump vec3 InDiffuseColor;
uniform lowp int usetexture;
uniform lowp int overlayWireframe;
uniform sampler2D TSampler01;
uniform float LightIntensity; uniform vec3 LightColor; uniform vec3 LightPosition; uniform vec3 LightAtt;
uniform float AmbientIntensity; uniform vec3 AmbientColor;

// Valores de entrada
varying vec3 vNormal;
varying lowp vec2 UV;
varying highp vec3 Pos_ws;
varying vec3 LightDir_cs;
varying vec3 EyeDir_cs;

void main(void)
{
    vec4 DiffuseColor;

    // Propiedades TEMPORALES del material
    vec3 MaterialSpecularColor= InDiffuseColor + vec3(0.15, 0.15, 0.15);

    // Vamos a calcular lo referente a la iluminacion puntual
    vec3 vToLight= Pos_ws - LightPosition;
    float distToLight= length(vToLight);
    vToLight= normalize(vToLight);

    // Direccion de la luz desde el fragmento hasta la fuente
    vec3 l= normalize(LightDir_cs);
    vec3 E= normalize(EyeDir_cs);
    vec3 R= reflect(-l, normalize(vNormal));
    float cosAlpha= clamp(dot(E, R), 0.0, 1.0);

    float cosNL= clamp(dot(normalize(vNormal), -vToLight), 0.0 ,1.0);
    float LAtt= (LightAtt.x + LightAtt.y * distToLight + LightAtt.z * distToLight * distToLight);

    if (usetexture==1)
	DiffuseColor= vec4 (texture2D(TSampler01, UV));
    else
	DiffuseColor= vec4 (InDiffuseColor, 1.0);

    vec4 ResultColor= AmbientIntensity * vec4(AmbientColor, 1.0) // Ambiental
	    +(DiffuseColor * vec4(LightIntensity * cosNL * LightColor, 1.0))/LAtt // Difuso
	    +vec4(MaterialSpecularColor * LightColor * (LightIntensity / 2.0) * pow(cosAlpha, 5.0) / LAtt, 1.0); // Specular
		


    if (overlayWireframe==1)
	   gl_FragColor= vec4(1.0, 1.0, 1.0, 2.0) - ResultColor;
    else
	   gl_FragColor= ResultColor;
}
